<template>
  <div class="min-h-screen bg-gray-50">
    <!-- Header -->
    <header class="bg-white shadow-sm">
      <div class="mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <div class="flex justify-between items-center">
          <div class="flex items-center space-x-4" style="margin: 1rem;">
            <div class="flex items-center justify-center w-10 h-10 bg-blue-600 rounded-lg">
              <span class="text-white text-lg font-bold">擎</span>
            </div>
            <div style="margin-left: 1rem;">
              <h1 class="text-2xl font-bold text-gray-900" style="margin-bottom: 0;">工位管理</h1>
              <p class="text-sm text-gray-500" style="margin-bottom: 0;">自动化执行平台</p>
            </div>
          </div>
          
          <div class="flex items-center space-x-4">
            <a-badge :count="workstations.length" show-zero>
              <a-button type="text" size="large">
                <template #icon><AppstoreOutlined /></template>
              </a-button>
            </a-badge>
            
            <a-dropdown>
              <a-button type="text" size="large">
                <template #icon><UserOutlined /></template>
                <span class="ml-2">{{ userStore.user?.name || '用户' }}</span>
                <DownOutlined class="ml-1 text-xs" />
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="profile">
                    <UserOutlined />
                    个人信息
                  </a-menu-item>
                  <a-menu-divider />
                  <a-menu-item key="logout" @click="handleLogout">
                    <LogoutOutlined />
                    退出登录
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
        </div>
      </div>
    </header>

    <!-- Main Content -->
    <main class="mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- Sync Section -->
      <a-card class="mb-6 shadow-sm">
        <h2 class="text-lg font-semibold text-gray-900 mb-3">同步工位信息</h2>
        <p class="text-sm text-gray-500 mb-4">通过工位名称从云端同步工位配置信息</p>
        <div class="flex items-center gap-3">
          <a-input
            v-model:value="syncWorkstationName"
            placeholder="请输入工位名称"
            size="large"
            class="flex-1"
            @pressEnter="handleSync"
          >
            <template #prefix>
              <AppstoreOutlined class="text-gray-400" />
            </template>
          </a-input>
          <a-button 
            type="primary" 
            size="large"
            @click="handleSync"
            :loading="syncing"
            :icon="h(SyncOutlined)"
          >
            同步工位
          </a-button>
        </div>
      </a-card>

      <!-- Workstation Cards -->
      <div class="mb-4 flex items-center justify-between">
        <h2 class="text-xl font-semibold text-gray-900" style="margin: 1rem;">工位列表</h2>
        <a-button @click="loadWorkstations" :loading="loading">
          <template #icon><ReloadOutlined /></template>
          刷新
        </a-button>
      </div>

      <div v-if="loading && workstations.length === 0" class="text-center py-12">
        <a-spin size="large" />
        <p class="mt-4 text-gray-500">加载中...</p>
      </div>

      <div v-else-if="workstations.length === 0" class="text-center py-12">
        <a-empty description="暂无工位数据,请先同步工位信息" />
      </div>

      <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <a-card
          v-for="station in workstations"
          :key="station.id"
          hoverable
          class="shadow-sm hover:shadow-lg transition-shadow duration-300"
          @click="viewWorkstation(station.id)"
        >
          <template #title>
            <div class="flex items-center justify-between">
              <span class="font-semibold">{{ station.name }}</span>
              <a-tag :color="getStatusColor(station.status)">
                {{ getStatusText(station.status) }}
              </a-tag>
            </div>
          </template>

          <div class="space-y-3">
            <div class="flex items-start">
              <EnvironmentOutlined class="text-gray-400 mr-2 mt-1" />
              <div class="flex-1">
                <p class="text-sm text-gray-500">位置</p>
                <p class="text-sm font-medium text-gray-900">{{ station.config?.location || '未配置' }}</p>
              </div>
            </div>

            <div class="flex items-start">
              <ToolOutlined class="text-gray-400 mr-2 mt-1" />
              <div class="flex-1">
                <p class="text-sm text-gray-500">设备</p>
                <div class="flex flex-wrap gap-1 mt-1">
                  <a-tag
                    v-for="(device, index) in station.config?.devices || []"
                    :key="index"
                    class="text-xs"
                  >
                    {{ device }}
                  </a-tag>
                </div>
              </div>
            </div>
          </div>

          <template #actions>
            <a-button type="link" @click.stop="viewWorkstation(station.id)">
              查看详情
            </a-button>
          </template>
        </a-card>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, h } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  UserOutlined,
  LogoutOutlined,
  DownOutlined,
  AppstoreOutlined,
  SyncOutlined,
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EnvironmentOutlined,
  ToolOutlined
} from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import { useWorkstationStore } from '@/stores/workstation'
import { storeToRefs } from 'pinia'

const router = useRouter()
const userStore = useUserStore()
const workstationStore = useWorkstationStore()

const { workstations } = storeToRefs(workstationStore)
const loading = ref(false)
const syncWorkstationName = ref('')
const syncing = ref(false)

const getStatusColor = (status) => {
  const colors = {
    idle: 'default',
    running: 'processing',
    error: 'error',
    offline: 'warning'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    idle: '空闲',
    running: '运行中',
    error: '异常',
    offline: '离线'
  }
  return texts[status] || '未知'
}

const loadWorkstations = async () => {
  loading.value = true
  try {
    await workstationStore.fetchWorkstations()
  } catch (error) {
    message.error('加载工位列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleSync = async () => {
  if (!syncWorkstationName.value.trim()) {
    message.warning('请输入工位名称')
    return
  }

  syncing.value = true
  try {
    await workstationStore.syncWorkstation(syncWorkstationName.value)
    message.success('工位同步成功!')
    syncWorkstationName.value = ''
  } catch (error) {
    message.error('工位同步失败')
    console.error(error)
  } finally {
    syncing.value = false
  }
}

const viewWorkstation = (id) => {
  router.push(`/workstations/${id}`)
}

const handleLogout = async () => {
  try {
    await userStore.logout()
    message.success('已退出登录')
    router.push('/login')
  } catch (error) {
    console.error('Logout error:', error)
    // 即使API失败也跳转到登录页
    router.push('/login')
  }
}

onMounted(() => {
  loadWorkstations()
})
</script>

<style scoped>
:deep(.ant-card-actions) {
  background: transparent;
}
</style>

